/*
    duskdawn-map <map.js>
    Copyright (C) 2011  Joshua Redfield

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>
*/
//Request key from background.html
chrome.extension.sendRequest({localstorage: "duskdawnkey"}, function(response) {
    var iframe = document.createElement("iframe");
    var space = document.createElement("br");
    var whereto = document.getElementById("debug");
    var frameid = document.getElementById("injected_frame");
    var DAWN = response.duskdawnkey; //Set DuskDawn Key

    //Setup iframe attributes
    iframe.setAttribute("id","injected_frame");
    iframe.setAttribute("src", 'http://d2n.duskdawn.net/map?key='+DAWN);
    iframe.setAttribute("width","100%");
    iframe.setAttribute("height","425");
    iframe.setAttribute("frameborder","0");
    iframe.setAttribute("scrolling","auto");

    //update zone when map is loaded
    function zoneupdate() {
        var http = new XMLHttpRequest();
        var zone_update = "http://d2n.duskdawn.net/zone?key="+DAWN+"&action=UPDATE_ZONE";
        http.open("POST", zone_update, true);
        http.send(zone_update);
    }

    // Check and see if iframe is already on page
    if (frameid)
    { //yes? Remove iframe
        zoneupdate();
        whereto.removeChild(whereto.childNodes[0]); //Remove spacer
        whereto.removeChild(whereto.childNodes[0]); //Remove iframe
    }
    else // no? Inject iframe
    {
        zoneupdate();
        whereto.appendChild(space); //Add spacer
        whereto.appendChild(iframe); //Add iframe
        document.body.insertBefore(space, whereto);
        document.body.insertBefore(iframe, whereto);
    }
});
